package org.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.reggie.entry.Category;
import org.example.reggie.result.ResultData;
import org.example.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品及套餐分类 controller控制类
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品分类
     * @param category
     * @return
     */
    @PostMapping("/insert")
    public ResultData<String> save(@RequestBody Category category){
        categoryService.save(category);
        return ResultData.success("插入成功",null);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public ResultData<Page<Category>> FindByPage(Integer pageNum,Integer pageSize){
        Page pageInfo = new Page(pageNum,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByDesc(Category::getSort);
        //查询到的数据自动那个填充到pageInfo
        categoryService.page(pageInfo,queryWrapper);
        return ResultData.success("查询成功",pageInfo);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public ResultData<String> delete(Long id){
        //删除之前，判断段是否已经被其他模块引用
        categoryService.remove(id);
        return ResultData.success("删除成功");
    }

    /**
     * 根据id更新
     * @param category
     * @return
     */
    @PutMapping("/update")
    public ResultData<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return ResultData.success("修改成功");
    }

    /**
     * 菜品新增页面菜品下拉列表
     * @param category
     * @return
     */
    @GetMapping("/list")
    public ResultData<List> list(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return ResultData.success("查询成功",list);
    }
}
